package com.group01.community.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : guoyuan
 * date : @since 2025-05-01
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseResult<T> {

    private ResponseStatus status;

    private T data;

    /**
     * 返回成功对象
     * @param data 数据
     * @param <T> 泛型参数
     * @return 结果
     */
    public static <T> ResponseResult<T> ok(T data) {
        return new ResponseResult<>(ResponseStatus.OK, data);
    }

    /**
     * 返回错误信息
     * @param status 错误码
     * @return 错误信息
     */
    public static ResponseResult<String> error(ResponseStatus status) {
        return new ResponseResult<>(status, status.getMessage());
    }

    /**
     * 返回错误信息
     * @param status 错误码
     * @param msg 错误信息
     * @return 返回结果
     */
    public static ResponseResult<String> error(ResponseStatus status, String msg) {
        return new ResponseResult<>(status, msg);
    }

    public static ResponseResult<String> error(String msg) {
        return new ResponseResult<>(ResponseStatus.INTERNAL_ERROR, msg);
    }

    /**
     * 向流中输出结果
     * @param resp 响应
     * @param result 结果
     */
    public static void write(HttpServletResponse resp, ResponseResult result) {
        resp.setContentType("application/json;charset=UTF-8");
        try {
            String s = new ObjectMapper().writeValueAsString(result);
            resp.getWriter().print(s);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                resp.getWriter().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
